package czk.concrent.enjoyModelWithNotLock.atomicStampRefence;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 引用版本号来解决ABA问题
 * @Author:ChenZhangKun
 * @Date: 2020/6/14 21:21
 */
public class Test1 {
    public static void main(String[] args) {
        AtomicStampedReference<String> atomicStampedReference=new AtomicStampedReference<>("A",0);
        // 主线程拿到值和版本号
        String reference = atomicStampedReference.getReference();
        int stamp = atomicStampedReference.getStamp();
        // 新线程去修改
        new Thread(()->{
            atomicStampedReference.compareAndSet(reference,"B",stamp,stamp+1);
            System.out.println("改成了 "+atomicStampedReference.getReference());
            atomicStampedReference.compareAndSet(atomicStampedReference.getReference(),"A",atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1);
            System.out.println("改回了 "+atomicStampedReference.getReference());
        }).start();
        try {
            Thread.sleep(2*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 主线程尝试修改
        boolean b = atomicStampedReference.compareAndSet(reference, "B", stamp, stamp + 1);
        System.out.println(b==true?"cas成功":"cas失败");
    }
}
